package routers

import (
	"server/global"
	"server/internal/service"
	"server/pkg/app"
	"server/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type ChainAccount struct{}

func NewChainAccount() *ChainAccount {
	return &ChainAccount{}
}

func (ca *ChainAccount) NewChainAccount(c *gin.Context) {
	param := &struct {
		ChainName string `form:"chainName" binding:"required"`
		Pwd       string `form:"pwd" binding:"required"`
		Username  string `form:"username" binding:"required"`
	}{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errRsp)
		return
	}

	svc := service.New(c.Request.Context())
	addr, err := svc.NewChainAccount(param.ChainName, param.Pwd, param.Username)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorNewChainAccountFail)
		return
	}

	response.ToSuccessResponse(addr)
}

func (ca *ChainAccount) GetChainAccounts(c *gin.Context) {
	param := &struct {
		Username string `form:"username" binding:"required"`
	}{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errRsp)
		return
	}

	svc := service.New(c.Request.Context())
	accounts, err := svc.GetChainAccounts(param.Username)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorGetChainAccountsFail)
		return
	}

	response.ToSuccessResponse(accounts)
}
